// components/buy-pop.js
import goodsApi from '../../service/goodsApi'
import { reLogin } from '../../service/request'
const app = getApp()
const SUCCESS_CODE = app.globalData.codeConfig.errCode.SUCCESS_CODE
let iptNumberComponent // 数字输入框组件实例
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    showBuyPopup: {
      type: Boolean,
      value: false,
    },// 是否展示购买弹窗
    specsBtn: {
      type: Boolean,
      value: false,
    },// 规格弹窗是否是点击规格按钮 
    goodsInfo: {
      type: Object,
      value: {},
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    specList: [], // 所有属性
    selectedList: [], // 已选列表
    goodsInfoList: [], // 可用组合列表
    isTalent: false, // 是否为店主
    maxStock: '9999',
    btnText: '确认',
    noStockClass: false, // 切换按钮缺货状态 class
    getAttrFlag: false, // 是否获取过 商品属性
    confirmLoading: false, // 确认按钮的 loading
    hadAuthFlag: false, // 是否授权过用户信息
    spinning: false, // 购买弹窗的 loading
    goodsId: '',
    orderInfo: { // 订单信息
        name: '',
        imageUrl: '',
        price: '',
        goodsId: '',
        quantity: '1',
        selectedTxt: '',
        stock: '9999',
        talentId: '',
        goodsType: ''
    },
  },
  
  // 在组件实例进入页面节点树时执行
  attached: function() {
  },

  // 在组件在视图层布局完成后执行
  ready: function() {
    iptNumberComponent = this.selectComponent('#ipt-quantity') // 获取数字输入框实例
    this.checkStatus()
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 登录状态的检查
    checkStatus () {
      let that = this
      // 判断是否有授权，有授权的话从回调调用方法初始化数据
      // 无授权的话直接调用方法初始化数据
      wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            that.setData({
              hadAuthFlag: true
            })
          }
        }
      })
    },
    // 
    onRushBuy() {
      console.log(this.data.specList, '123');
      if (this.data.goodsId != this.data.goodsInfo.goodsId) {
        this.setData({
          goodsId: this.data.goodsInfo.goodsId,
          ['orderInfo.price']: this.data.goodsInfo.realPrice
        })
        this.getGoodsAttr()
      }
    },

    // 获取商品属性
    getGoodsAttr () {
      let that = this
      that.setData({
        spinning: true,
        specList: [],
        selectedList: []
      })
      goodsApi.getGoodsAttr({
        goodsId: that.data.goodsInfo.goodsId
      }).then((res) => {
        if (SUCCESS_CODE === res.data.errCode) {
          // 对获取到的数据添加 selected 属性
          let { specList } = res.data.data
          console.log(res.data, 'res.data');
          let picUrl = ''
          specList.forEach((value, i) => {
            value.detailList.forEach((item, j) => {
              if (i === 0 && j === 0) { // 默认选中第一行的第一个
                picUrl = item.picUrl
                item.selected = true
              } else {
                item.selected = false
              }
            })
          })
          that.setData({
            getAttrFlag: true,
            spinning: false,
            specList: [...specList],
            goodsInfoList: [...res.data.data.goodsInfoList],
            ['orderInfo.buyNowImg']: picUrl
          })
          that.initSelectedList()
        } else {
          that.setData({
            getAttrFlag: false,
            spinning: false,
          })
        }
      }).catch((res) => {
        that.setData({
          getAttrFlag: false,
          spinning: false
        })
      })
    },

    // 初始化 selectedList 
    initSelectedList () {
      let that = this
      let obj = { id: '#' }
      for (let i = 0; i < that.data.specList.length; i++) {
        if (i === 0) { // 默认选中第一行的第一个
          let id = that.data.specList[0].detailList[0].id
          let txt = that.data.specList[0].detailList[0].value
          that.data.selectedList.push({id, txt})
        } else {
          that.data.selectedList.push({...obj})
        }
      }
      that.generateSelectedText() // 拼接已选字符串
      that.checkStock() // 检查库存
    },

    // 选择商品属性
    handleSelected (e) {
      let that = this
      let index = e.target.dataset.index
      let id = e.detail.id
      let txt = e.detail.txt
      if (index === 0) {
        that.setData({
          ['orderInfo.buyNowImg']: e.detail.picUrl
        })
      }
      that.setData({
        [`selectedList[` + index + `].id`]: id,
        [`selectedList[` + index + `].txt`]: txt
      })
      that.generateSelectedText()
      that.checkStock()
    },

    // 生成已选择属性的文本字符串
    generateSelectedText () {
      let that = this
      let str = '已选'
      that.data.selectedList.forEach((value, index) => {
        if (value.txt) {
          if (index === (that.data.selectedList.length -1)) {
            str = str + value.txt
          } else {
            str = str + value.txt + "，"
          }
        }
      })
      that.setData({
        ['orderInfo.selectedTxt']: str
      })
    },

    // 生成已选属性的字符串 类似 1-2 
    generateSelectedCombination () {
      let that = this
      if (that.data.selectedList.length === 0) {
        return ''
      } else {
        let tempList = [...that.data.selectedList]
        let checkStr = ''
        tempList.forEach((value, index) => {
          if (index !== (tempList.length - 1)) {
            checkStr = checkStr + value.id + '-'
          } else {
            checkStr += value.id
          }
        })
        return checkStr
      }
    },

    // 判断库存是否可以购买
    checkStock () {
      let that = this
      let checkStr = that.generateSelectedCombination()
      if (checkStr === '') return false
      // 如果还有 “#” 说明还有属性未选择
      if (checkStr.split('-').indexOf('#') !== -1) return false
      // 从可用组合列表中筛选符合条件的元素
      let checkResultArr = that.data.goodsInfoList.filter((value) => value.combination === checkStr)
      if (checkResultArr.length > 0) { // 有符合条件的
        let goodsInfo = {...checkResultArr[0]}
        if (goodsInfo.stock > 0) {
          // 有这个货，也有库存
          console.log(goodsInfo)
          this.setData({
            btnText: '确认',
            noStockClass: false,
            name: goodsInfo.name,
            maxStock: goodsInfo.stock // 将数字输入框允许的最大值设置为当前商品的库存量
          })
          console.log('可购买')
          console.log('当前商品库存为： ', goodsInfo.stock)
          // 若当前输入的大于库存量，设置为库存量
          if (that.data.orderInfo.quantity > goodsInfo.stock) {
            that.setData({
              ['orderInfo.quantity']: goodsInfo.stock
            })
          }
          // 调用数字输入框组件的方法更新 sub 和 add 按钮禁用状态
          iptNumberComponent.updated(that.data.orderInfo.quantity)
          // 填入数据
          that.setData({
            ['orderInfo.imageUrl']: goodsInfo.picUrl,
            ['orderInfo.goodsId']: goodsInfo.goodsId,
            ['orderInfo.price']: goodsInfo.price,
            ['orderInfo.name']: goodsInfo.name,
            ['orderInfo.stock']: goodsInfo.stock,
            ['orderInfo.expressFee']: that.data.goodsInfo.expressFee,
            ['orderInfo.goodsType']: that.data.goodsInfo.goodsType,
          })
          return true
        } else { // 有这个货，但是库存没了的
          // 库存为零的，填入数据，为了保证切换时价格等会变化
          that.setData({
            ['orderInfo.imageUrl']: goodsInfo.picUrl,
            ['orderInfo.goodsId']: goodsInfo.goodsId,
            ['orderInfo.price']: goodsInfo.price,
            ['orderInfo.name']: goodsInfo.name,
            ['orderInfo.stock']: goodsInfo.stock,
            ['orderInfo.expressFee']: that.data.goodsInfo.expressFee,
            ['orderInfo.goodsType']: that.data.goodsInfo.goodsType,
            maxStock: '9999',
            btnText: '缺货',
            noStockClass: true
          })
          // 调用数字输入框组件的方法更新 sub 和 add 按钮禁用状态
          iptNumberComponent.updated(that.data.orderInfo.quantity)
          console.log('不可购买')
          return false
        }
      } else { // 无符合条件的，即 “无货” 的 （就没这个货）    
        that.setData({
          maxStock: '9999',
          btnText: '缺货',
          noStockClass: true
        })
        // 调用数字输入框组件的方法更新 sub 和 add 按钮禁用状态
        iptNumberComponent.updated(that.data.orderInfo.quantity)
        console.log('不可购买')
        return false
      }
    },

    // 购买数量变化
    handleQuantityChange (e) {
        let that = this
        that.setData({
        ['orderInfo.quantity']: e.detail.value
        })
    },
    // 处理加号禁用时的点击
    handleDisableAdd () {
        if ((this.data.orderInfo.quantity - 0) === 9999) {
        wx.showToast({title: '最多购买 9999 个', icon: 'none'})
        } else {
        wx.showToast({title: '库存不足', icon: 'none'})
        }
    },

    /**
     * 检测哪些没选
     * 检测生成的 id 组合字符串中是否有 # ，有的话获取下标
     */
    checkSelect () {
      let that = this
      let checkStr = that.generateSelectedCombination()
      let resIndex = checkStr.split('-').indexOf('#')
      if (resIndex !== -1) {
        wx.showToast({
          title: '请选择' + that.data.specList[resIndex].title,
          icon: 'none',
          duration: 1500
        })
        return false
      }
      return true
    },

    // 点击 【确认】 按钮
    handleConfirmBuy () {
      let that = this
      if (that.data.btnText !== '缺货') {
        that.showConfrimLoading()
      }
      if (that.data.hadAuthFlag) {
        console.log('授权过')
        // 检测选择、库存和数量
        if (!that.checkSelect() || !that.checkStock() || (that.data.orderInfo.quantity <= 0)) {
          that.hideConfrimLoading()
          return
        }
        that.hideConfrimLoading()
        app.globalData.orderInfo = {...that.data.orderInfo}
        if (that.data.specsBtn) {
          that.setData({
            showBuyPopup: false
          })
        } else {
          wx.navigateTo({
            url: `/pages/confirmOrder/confirmOrder`
          })
        }
      }
    },

    // 授权回调
    bindGetUserInfo (e) {
      let that = this
      that.showConfrimLoading()
      console.log(e.detail.userInfo)
      if (!!e.detail.userInfo) { // 同意授权-并登陆
        wx.setStorageSync('hadAuthFlag', true)
        app.globalData.userInfo = e.detail.userInfo
        app.globalData.hadAuthUserInfo = true
        reLogin().then(() => {
          that.hideConfrimLoading()
          that.setData({
            hadAuthFlag: true
          })
          that.handleConfirmBuy()
          console.log(app.globalData.userInfo)
        }).catch((res) => {
          that.hideConfrimLoading()
        })
      } else { // 不同意授权
        that.hideConfrimLoading()
        wx.setStorageSync('hadAuthFlag', false)
        that.setData({
          hadAuthFlag: false
        })
      }
    },

    // 显示 确定 按钮的 loading
    showConfrimLoading () {
      this.setData({
        confirmLoading: true
      })
    },
    // 隐藏 确定 按钮的 loading
    hideConfrimLoading () {
      this.setData({
        confirmLoading: false
      })
    },

    // 关闭立即抢购弹窗
    closeBuyPopup() {
      this.setData({
          showBuyPopup: false,
          // specList: [],
          // selectedList: []
      })
    },
  }
})
